package com.yizisu.library.ad.impl.applovin

import androidx.lifecycle.MutableLiveData
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxError
import com.applovin.mediation.MaxReward
import com.applovin.mediation.MaxRewardedAdListener
import com.applovin.mediation.ads.MaxRewardedAd
import com.yizisu.library.ad.IAdRewardStatus
import com.yizisu.library.ad.IAdStatus

class ApplovinVideoListener(private val rewardedAd: MaxRewardedAd) : MaxRewardedAdListener {
    var rewardListener: Function1<IAdRewardStatus, Unit>? = null
    val statusData = MutableLiveData<IAdStatus>()


    override fun onRewardedVideoStarted(ad: MaxAd?) {

    }

    override fun onRewardedVideoCompleted(ad: MaxAd?) {

    }

    override fun onAdLoaded(ad: MaxAd?) {
        statusData.postValue(IAdStatus.Success)
    }

    override fun onAdLoadFailed(adUnitId: String?, error: MaxError?) {
        statusData.postValue(IAdStatus.Error)
    }

    override fun onUserRewarded(ad: MaxAd?, reward: MaxReward?) {
        rewardListener?.invoke(IAdRewardStatus.Success)
        rewardListener = null
    }

    override fun onAdDisplayFailed(ad: MaxAd?, error: MaxError?) {
        rewardedAd.loadAd()
        statusData.postValue(IAdStatus.Loading)
    }

    override fun onAdDisplayed(ad: MaxAd?) {
        rewardListener?.invoke(IAdRewardStatus.OpenAd)
    }

    override fun onAdHidden(ad: MaxAd?) {
        rewardListener?.invoke(IAdRewardStatus.Cancel)
        rewardListener = null
        rewardedAd.loadAd()
        statusData.postValue(IAdStatus.Loading)
    }

    override fun onAdClicked(ad: MaxAd?) {
    }
}